package fr.seba.wawadroid.proxyweb.parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import fr.seba.wawadroid.proxyweb.to.WawaPost;

public class PostParser {

	private static final Pattern PATTERN_HREF = Pattern.compile("<a\\b[^>]*href=\".*id=([0-9]*)\">(.*?)</a>");

	private static final Pattern PATTERN_USER = Pattern.compile("<span class=\"byuser\">par&nbsp;(.*?)</span>");
	
	private static final Pattern PATTERN_READER = Pattern.compile("<td class=\"tc3\">([0-9]+)</td>");
	
	private static final Pattern PATTERN_ANSWER = Pattern.compile("<td class=\"tc2\">([0-9]+)</td>");
		
	public static WawaPost getPost(String postContent) {

		WawaPost aWawaPost = new WawaPost();
		
		Matcher matcher = PATTERN_HREF.matcher(postContent);
		if (matcher.find()) {
			if (matcher.groupCount() == 2) {
				aWawaPost.setId(new Long(matcher.group(1)));
				aWawaPost.setTitle(matcher.group(2));
			}
		}

		matcher = PATTERN_USER.matcher(postContent);
		if(matcher.find()){
			if(matcher.groupCount() == 1){
				aWawaPost.setUser(matcher.group(1));
			}
		}

		matcher = PATTERN_READER.matcher(postContent);
		if(matcher.find()){
			if(matcher.groupCount() == 1){
				aWawaPost.setRead(new Integer(matcher.group(1)));
			}
		}
		
		matcher = PATTERN_ANSWER.matcher(postContent);
		if(matcher.find()){
			if(matcher.groupCount() == 1){
				aWawaPost.setAnswers(new Integer(matcher.group(1)));
			}
		}
		
		return aWawaPost;

	}

}
